package com.hzw.saas.service.ds.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzw.saas.api.ds.ISyncConfigService;
import com.hzw.saas.api.ds.bo.SyncConfigBo;
import com.hzw.saas.api.ds.query.SyncConfigQuery;
import com.hzw.saas.common.util.MapperUtil;
import com.hzw.saas.common.util.SnowFlakeUtil;
import com.hzw.saas.service.ds.mapper.SyncConfigMapper;
import com.hzw.saas.service.ds.model.SyncConfig;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class SyncConfigServiceImpl extends ServiceImpl<SyncConfigMapper, SyncConfig> implements ISyncConfigService, IService<SyncConfig> {

    @Override
    public Boolean modifySyncConfig(SyncConfigQuery syncConfigQuery) {
        SyncConfig addSyncConfig = MapperUtil.nf().map(syncConfigQuery, SyncConfig.class);
        Optional<SyncConfig> dbSyncConfigOp = getOneDb(syncConfigQuery);
        if (dbSyncConfigOp.isPresent()) {
            SyncConfig dbSyncConfig = dbSyncConfigOp.get();
            dbSyncConfig.setAllowRule(syncConfigQuery.getAllowRule());
            dbSyncConfig.setIgnoreRule(syncConfigQuery.getIgnoreRule());
            dbSyncConfig.setEditorId(syncConfigQuery.getUserId());
            dbSyncConfig.setUpdateTime(null);
            return super.updateById(dbSyncConfig);
        } else {
            addSyncConfig.setPid(SnowFlakeUtil.nextIdStr());
            addSyncConfig.setCreatorId(syncConfigQuery.getUserId());
            return super.save(addSyncConfig);
        }
    }

    @Override
    public SyncConfigBo getSyncConfig(SyncConfigQuery syncConfigQuery) {
        SyncConfig syncConfig = getOneDb(syncConfigQuery)
                .orElseGet(
                        () -> new SyncConfig().setAllowRule(StrUtil.EMPTY).setIgnoreRule(StrUtil.EMPTY)
                );
        return MapperUtil.nf().map(syncConfig, SyncConfigBo.class);
    }

    private Optional<SyncConfig> getOneDb(SyncConfigQuery syncConfigQuery) {
        SyncConfig dbSyncConfig = super.lambdaQuery()
                .eq(SyncConfig::getUserId, syncConfigQuery.getUserId())
                .eq(SyncConfig::getClientType, syncConfigQuery.getClientType())
                .last(" limit 1")
                .one();
        return Optional.ofNullable(dbSyncConfig);
    }
}
